package com.kj.report.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jayway.jsonpath.JsonPath;

import com.kj.report.model.Device;
import com.kj.report.model.PhysicalConditionView;
import com.kj.report.model.UserInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.ClientProtocolException;

import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

import static java.util.regex.Pattern.compile;

public class ReportBaseUtil {

    /**
     * 获取tokenkey
     * @param agentId
     * @param agentKey
     * @return
     */
    public static String getTokenKey(RedisUtils redisUtils,String url,String agentId,String agentKey){
        String redisResult = redisUtils.get("kjToken100000001");
        if (redisResult != null&&!redisResult.equals("null")&& StringUtils.isNotBlank(redisResult)){
            return redisResult;
        }
        Map<String,String> param = Maps.newHashMap();
        param.put("agentId",agentId);//代理人ID
        param.put("agentKey",agentKey);//代理人key

        param.put("timestamp",String.valueOf(System.currentTimeMillis()));//时间戳
        param.put("version","2.0");
        String result = "";
        try {
            result = HttpUtils.sendPostBuffer(url+"/api/v2/creatToken", JSON.toJSONString(param));
        } catch (Exception e) {
           throw new IllegalArgumentException("请求异常");
        }
        if(StringUtils.isNotBlank(result)){
            JSONObject jsonObject = JSON.parseObject(result);
            String token = String.valueOf(jsonObject.get("token"));
            redisUtils.setString("kjToken100000001",token,3600);
            return  result;
        }
        return result;

    }
    /**
     *  获取标准建议
     * @param redisUtils
     * @param token
     * @return
     */
    public static String getStanPropose (RedisUtils redisUtils,String url,String token) {
        String redisResult = redisUtils.get(token + "stanPropose");
        if (redisResult != null && redisResult != "")
            return redisResult;
        String result = "";
        try {
            result = HttpUtils.sendPostNotParam(url+"/api/v2/IFI_03?token=" + token);
        } catch (Exception e) {
            throw new IllegalArgumentException("请求异常");
        }
        if (StringUtils.isNotBlank(result)) {
            String proposeStr = JSON.parseObject(result, String.class);
            redisUtils.set(token + "stanPropose", proposeStr, 30);
            return result;
        }
        return result;
    }


    /**
     * 获取新版建议
     * @param redisUtils
     * @param token
     * @return
     */
    public static String getNewPropose (RedisUtils redisUtils,String url,String token) {
        String redisResult = redisUtils.get(token + "newPropose");
        if (redisResult != null && redisResult != "")
            return redisResult;
        String result = "";
        String proposeStr = "";
        try {
            result = HttpUtils.sendPostNotParam(url+"/api/v2/IFI_04?token=" + token);
        } catch (Exception e) {
            throw new IllegalArgumentException("请求异常");
        }
        if (StringUtils.isNotBlank(result)) {
            List<HashMap<String,Object>> data = JsonPath.read(result,"$.data");
            List<HashMap<String,Object>> relation = JsonPath.read(result,"$.relation");
            for (Map<String, Object> relationMap : relation) {
                String indexTypeIds = String.valueOf(relationMap.get("indexTypeIds"));
                String classify = String.valueOf(relationMap.get("classify"));
                String[] relaValue = indexTypeIds.split(",");
                List<Object> arrayList= Lists.newArrayList();

                for (String isndexTypeId : relaValue) {
                    for (Map<String, Object> dataMap : data) {
                        String indexTypeId = String.valueOf(dataMap.get("indexTypeId"));
                        String indexType = String.valueOf(dataMap.get("indexType"));
                        if(isndexTypeId.equals(indexTypeId) & classify.equals(indexType)){
                            arrayList.add(JSON.toJSON(dataMap));
                            break;
                        }
                    }
                }
                String s = JSON.toJSONString(arrayList);
                relationMap.put("indexTypeIds", JSON.toJSON(arrayList));
            }
            HashMap<String, Object> relationMap = new HashMap<String, Object>();
            relationMap.put("relation", JSON.toJSON(relation));
            proposeStr = JSON.toJSONString(relationMap);
            redisUtils.set(token + "newPropose", proposeStr, 30);
            return proposeStr;
        }
        return proposeStr;
    }
    /**
     *获取报告数据
     * @param reportId
     * @param uAge
     * @param uId
     * @return
     */
    public static String  getReportData(String url,String reportId,Integer uAge,String uId,String token){
        Map<String,String> param = Maps.newHashMap();
        param.put("reportId",reportId);
        param.put("timestamp",getTimestampStr());
        param.put("uAge",uAge.toString());
        param.put("uId",uId);
        param.put("version","2.0");
        String result = "";
        try {
            result = HttpUtils.sendPostBuffer(url+"/api/v2/IFI_01?token="+token, JSONObject.toJSONString(param));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    public static String getTimestampStr(){
        SimpleDateFormat sq = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sq.format(System.currentTimeMillis());
    }

    public static String getTimestampStr(Date date){
        SimpleDateFormat sq = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sq.format(date);
    }
    /**
     * 获取指标和说明
     * @param redisUtils
     * @param tokenKey
     * @return
     */
    public static String getIndicators(RedisUtils redisUtils,String url,String tokenKey){
        String redisResult = redisUtils.get(tokenKey + "Indicators");
        if (redisResult != null && redisResult != ""){
            return redisResult;
        }
        String result="";
        try {
            result = HttpUtils.sendPostNotParam(url+"/api/v2/IFI_02?token="+tokenKey);
        } catch (IOException e) {
            throw new IllegalArgumentException("请求异常");
        }
        if (StringUtils.isNotBlank(result)) {
            String proposeStr = JSON.parseObject(result, String.class);
            redisUtils.set(tokenKey + "Indicators", proposeStr, 30);
            return result;
        }
        return result;
    }

    /**
     * 身体状况
     * @param InspectId
     * @param UserId
     * @param device
     * @param psTargets
     * @param normMap
     * @return
     */
    public static List<PhysicalConditionView> getPsList(String InspectId, Integer UserId, Device device, List<Map<String,Object>> psTargets, Map<String,Map<String,Object>> normMap){
        List<PhysicalConditionView> physicalConditionViewList = new ArrayList<PhysicalConditionView>();
        for (Map<String, Object> psTarget : psTargets) {
            PhysicalConditionView ps = new PhysicalConditionView();

            String targetId = String.valueOf(psTarget.get("targetId"));
            String abLive = String.valueOf(psTarget.get("abLive"));
            //异常等级
            if(isNumeric(abLive)){
                int abnormalLevel = Integer.parseInt(abLive);
                ps.setAbnormalLevel(abnormalLevel);
            }else{
                //酸碱度
                ps.setAbnormalLevel(0);
                ps.setAnalysisResults(abLive);
            }
            Map<String, Object> targetMap = normMap.get(targetId);
            String explain = String.valueOf(targetMap.get("explain"));
            String name = String.valueOf(targetMap.get("name"));
            //解释
            ps.setExplain(explain);
            //指标名称
            ps.setTargetName(name);
            //检查记录ID
            ps.setInspectId(InspectId);
            //用户ID
            ps.setUserId(UserId);
            //指标ID
            ps.setTargetId(Integer.parseInt(targetId));
            //1 大机器 2 桌面机
            ps.setDeviceType(device.getDeviceType()==1 ? 1 : 2);

            physicalConditionViewList.add(ps);
        }
       return physicalConditionViewList;
    }

    /**
     * 判断字符串是否是数字
     * @param str
     * @return
     */
    public static boolean isNumeric(String str) {
        Pattern pattern = compile("[0-9]*");
        return pattern.matcher(str).matches();
    }

    /**
     * 食谱
     * @param recipesUrl
     * @param recipesList
     * @param reportId
     * @return
     */
    public static String getRecipes(String recipesUrl,List<Map<String, String>> recipesList, String reportId) {
        JSONObject map = new JSONObject();
        map.put("data", recipesList);
        map.put("reportId", reportId);
        String recipesStr = "";
        String s = map.toJSONString();
        try {
            String url = recipesUrl + "v1/billList/getBillList";
            String result = HttpUtils.sendPostBuffer(url, map.toJSONString());
            JSONObject jsonObject = JSONObject.parseObject(result);
            boolean bool = ("0").equals(jsonObject.get("code").toString());
            if (bool) {
                recipesStr = jsonObject.get("data").toString();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return recipesStr;
    }
    /**
     * 读取3.0数据，存入redis
     */
    public void readStream(RedisUtils redisUtils) {
        String reportBaseData = redisUtils.get("reportBaseData");
        if (reportBaseData==null){
            redisUtils.set("reportBaseData", Basedata.basedata,30);
        }

    }

    /**
     * 获取BMI的值
     * @param userInfo
     * @return
     */
    public static double getBmiValue(UserInfo userInfo){
        if (userInfo == null){
            throw new IllegalArgumentException("用户信息为空");
        }
        //计算BMI值
        Integer height = userInfo.getHeight();
        Double weight = userInfo.getWeight();
        if(weight == null && height == null){
            return 0;
        }
        DecimalFormat df = new DecimalFormat("0.00");
        double newHeight = Double.parseDouble(df.format((double)height/100));
        double bmiValue = Double.parseDouble(df.format(weight/(newHeight*newHeight)));
        return bmiValue;
    }
}
